//
//  CZComposeDetailController.swift
//  GZWeibo007
//
//  Created by shan on 15/12/24.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit
import SVPullToRefresh

enum CZCommentCellReuseIdentifier: String {
    case NoneComment = "NoneComment"
    case DidComment = "DidComment"
    case LoadingComment = "LoadingComment"
}

class CZComposeDetailController: UIViewController, UITableViewDataSource, UITableViewDelegate, CZStatusForWardCellDelegate, CZStatusBottomViewDelegate, CZCommentCellHeaderViewDelegate {
    // MARK: -属性
    // 模型属性
    var status: CZStatus?
    
    var comments: [CZComment]? {
        didSet{
            tableView.reloadData()
        }
    }
    
    // MARK: - 方法
    /// 返回ViewController方法
    class func detailVC(status: CZStatus) -> CZComposeDetailController{
        let detailVC = CZComposeDetailController()
        detailVC.status = status
        return detailVC
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "微博详情"
        
        prepareUI()
        
    }
    private func prepareUI() {
        view.addSubview(tableView)
        view.addSubview(botomView)
        
        tableView.ff_Fill(view, insets: UIEdgeInsets(top: 0, left: 0, bottom: 44, right: 0))
        
        botomView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: tableView, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
    }
    
    /// 加载最新数据
    func loadNewComment() {
        let since_id = comments?.first?.id ?? 0
        let max_id = 0
        
        if comments == nil {
            comments = [CZComment]()
        }
        let loadingModel = CZComment(loading: true)
        comments?.insert(loadingModel, atIndex: 0)
        //        tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 1), atScrollPosition: UITableViewScrollPosition.Top, animated: true)
        
        
        CZComment.loadingComment(status!.id, since_id: since_id, max_id: max_id) { (comment, error) -> () in
            self.comments?.removeFirst()
            if error != nil || comment == nil {
                print("获取评论数据出错\(error)")
                return
            }
            
            if comment!.count == 0 {
                // 没有数据直接返回
                print("没有评论")
                return
            }
            
            self.comments = since_id > 0 ? comment! + self.comments! : comment
        }
    }
    /// 加载更多数据
    func loadMoreComment() {
        let since_id = 0
        let max_id = comments?.last?.id ?? 0
        CZComment.loadingComment(status!.id, since_id: since_id, max_id: max_id) { (comment, error) -> () in
            // 关闭菊花
            self.tableView.infiniteScrollingView.stopAnimating()
            
            if error != nil || comment == nil{
                print("加载数据出错\(error)")
                return
            }
            if comment!.count == 0 {
                // 没有数据直接返回
                return
            }
            
            if let currentComment = self.comments {
                self.comments = currentComment + comment!
            }else{
                self.comments = comment!
            }
            
        }
    }
    
    // 底部按钮点击跳转方法
    func bottomViewDidClick() {
        let composeVC = CZForwardViewController()
        let composeNav = UINavigationController(rootViewController: composeVC)
        self.presentViewController(composeNav, animated: true, completion: nil)
    }
    
    //MARK: - 懒加载
    /// tableview
    private lazy var tableView: UITableView = {
        let tableview = UITableView()
        tableview.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
        // 指定数据源
        tableview.dataSource = self
        // 指定代理
        tableview.delegate = self
        // 注册tableViewCell
        tableview.registerClass(CZStatusNormalCell.self, forCellReuseIdentifier: CZStatusCellReuseIdentifier.StatusNormalCell.rawValue)
        tableview.registerClass(CZStatusForwardCell.self, forCellReuseIdentifier: CZStatusCellReuseIdentifier.StatusForwardCell.rawValue)
        tableview.registerClass(CZCommentNoneCell.self, forCellReuseIdentifier: CZCommentCellReuseIdentifier.NoneComment.rawValue)
        tableview.registerClass(CZCommentCell.self, forCellReuseIdentifier: CZCommentCellReuseIdentifier.DidComment.rawValue)
        tableview.registerClass(CZCommentLoadingCell.self, forCellReuseIdentifier: CZCommentCellReuseIdentifier.LoadingComment.rawValue)
        
        // 设置tableview分割线
        tableview.separatorStyle = UITableViewCellSeparatorStyle.None
        
        tableview.addInfiniteScrollingWithActionHandler({ () -> Void in
            print("加载更多数据")
            self.loadMoreComment()
        })
        return tableview
        }()
    
    /// 底部View
    private lazy var botomView: CZStatusBottomView = {
        let view = CZStatusBottomView()
        view.delegate = self
        return view
        
        }()
    
    /// cell头部View
    private lazy var headerView: CZCommentCellHeaderView = {
        let view = CZCommentCellHeaderView()
        view.delegate = self
        return view
    }()
}

// MARK: - 分类
extension CZComposeDetailController {
    // MARK: tableView数据源方法
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // 判断是第几组数据
        if section == 0 {
            return 1
        }
        // 第二组
        if comments == nil || comments?.count == 0 {
            return 1
        }else{
            return comments!.count
        }
        
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // 第一组
        if indexPath.section == 0 {
            // 获取cellId
            let cellID = status!.cellID()
            let cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! CZStatusCell
            cell.status = status
            cell.selectionStyle = UITableViewCellSelectionStyle.None
            // 判断Cell是否为转发微博
            if cell is CZStatusForwardCell {
                let forwardCell = cell as! CZStatusForwardCell
                // 指定代理
                forwardCell.delegate = self
            }
            
            return cell
        }
        // 第二组
        if comments == nil || comments!.count == 0 {
            // 如果评论模型数组为空返回无评论cell
            let cell = tableView.dequeueReusableCellWithIdentifier(CZCommentCellReuseIdentifier.NoneComment.rawValue)
            return cell!
        }
        let comment = self.comments![indexPath.row]
        
        if comment.loading == true {
            // 返回加载cell
            let cell = tableView.dequeueReusableCellWithIdentifier(CZCommentCellReuseIdentifier.LoadingComment.rawValue)
            return cell!
        }
        // 如果有数据返回有数据的cell
        let cell = tableView.dequeueReusableCellWithIdentifier(CZCommentCellReuseIdentifier.DidComment.rawValue) as! CZCommentCell
        cell.comment = comment
        return cell
    }
    
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 1{
            headerView.commentCount = CZComment.total_number ?? 0
            return headerView
        }
        return nil
    }
    
    // MARK: - tableview代理方法实现
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        // 第一组
        if indexPath.section == 0 {
            // 获取行高
            if let rowHeight = status?.rowHeight {
                return rowHeight
            }
            let cell = tableView.dequeueReusableCellWithIdentifier((status?.cellID())!) as! CZStatusCell
            let rowHeight = cell.rowHeight(status!)
            status?.rowHeight = rowHeight
            return rowHeight
        }
        // 第二组
        if comments == nil || comments?.count == 0 {
            // 没有数据返回固定行高
            return 120
        }
        
        let comment = comments![indexPath.row]
        
        if comment.loading == true {
            // 返回加载cell高度
            return 44
        }
        var rowHeight = comment.rowHeight
        // 判断有无缓存行高
        if rowHeight != nil {
            print("计算行高\(rowHeight)")
            return rowHeight!
        }
        // 没有缓存行高计算行高
        let cell = tableView.dequeueReusableCellWithIdentifier(CZCommentCellReuseIdentifier.DidComment.rawValue) as! CZCommentCell
        rowHeight = cell.rowHeight(comment)
        comment.rowHeight = rowHeight
        print("缓存行高\(rowHeight)")
        return rowHeight!
    }
    
    // 设置tableview尾部部View大小
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 {
            return 54
        }else{
            return 0
        }
    }
    
    // MARK: - 转发微博代理方法实现
    func statusForwardBkgButtonDidClick(status: CZStatus) {
        let detailVC = CZComposeDetailController.detailVC(status)
        detailVC.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(detailVC, animated: true)
    }
    
    // MARK: - 底部控件代理方法实现
    func modalCommentButtomClick() {
        let composeVC = CZCommentController()
        composeVC.status = status
        let composeNav = UINavigationController(rootViewController: composeVC)
        self.presentViewController(composeNav, animated: true, completion: nil)
    }
    
    func modalForwardButtonClick() {
        let composeVC = CZForwardViewController()
        let composeNav = UINavigationController(rootViewController: composeVC)
        composeVC.status = status
        self.presentViewController(composeNav, animated: true, completion: nil)
    }
    
    // MARK: - cell头部代理方法实现
    func commentCellHeaderViewCommentButtonDidClick() {
        // 加载更多数据
        loadNewComment()
    }
}
